package com.btm.controller;

import com.btm.config.IpRestrictConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/sql_execute")
public class IpRestrictController {

    @Autowired
    private IpRestrictConfig ipRestrictConfig;

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @GetMapping("/check")
    public Map<String, Object> checkDbIpSafety() {
        String dbIp = extractIpFromJdbcUrl(dbUrl);
        Map<String, Object> result = new HashMap<>();
        result.put("restricted", ipRestrictConfig.isDbIpUnsafe(dbIp));
        result.put("dbIp", "0.0.0.0");
        return result;
    }

    private String extractIpFromJdbcUrl(String jdbcUrl) {
        try {
            // 移除 jdbc: 前缀
            String url = jdbcUrl.substring(5);
            URI uri = URI.create(url);
            String host = uri.getHost();
            return host;
        } catch (Exception e) {
            // 如果解析失败，尝试使用简单的字符串处理
            try {
                return jdbcUrl.split("//")[1].split("/")[0].split(":")[0];
            } catch (Exception ex) {
                return "unknown";
            }
        }
    }
} 